var express = require('express');
var router = express.Router();
var cors = require('cors');

const whitelist = ['http://localhost:3001'];

//--------------------------- Simple Request --------------------------------------
//Configuring CORS w/ Dynamic Origin
var corsOptions = {
    origin: function (origin, callback) {
        if (whitelist.indexOf(origin) !== -1) {
            callback(null, true)
        } else {
            callback(new Error('Not allowed by CORS'))
        }
    }
}

router.get('/simple', cors(corsOptions), function (req, res, next) {
    res.json({
        state: 'Success'
    });
});

//--------------------------- Complex Request ---------------------------------------
//Configuring CORS Asynchronously
var corsOptionsDelegate = function (req, callback) {
    var corsOptions;
    if (whitelist.indexOf(req.header('Origin')) !== -1) {
        corsOptions = {
            origin: true,
            methods: ['POST'],
            credentials: true,
            maxAge: 3600
        } // reflect (enable) the requested origin in the CORS response
    } else {
        corsOptions = {
            origin: false,
            methods: ['POST'],
            credentials: true,
            maxAge: 3600
        } // disable CORS for this request
    }
    callback(null, corsOptions) // callback expects two parameters: error and options
};

router.options('/complex', cors(corsOptionsDelegate));
router.post('/complex', cors(corsOptionsDelegate), function (req, res, next) {
    res.json({
        info: `Hi ${req.body.name}, you are ${req.body.age} years old and you access another origin successful`
    });
});

module.exports = router;